import errors = require('feathers-errors')

const auth = require('feathers-authentication')
const jwt = require('feathers-authentication-jwt')
const local = require('feathers-authentication-local')
const { iff, iffElse } = require('feathers-hooks-common')
const moment = require('moment')

const authServicePath = 'authentication'
const userService = '/user'
const cookieName = 'kollway-jwt'

class CustomVerifier {

    constructor(app: any) {

    }
    // The verify function has the exact same inputs and 
    // return values as a vanilla passport strategy
    verify(req: any, payload: any, done: any) {
        let data = {//TODO 把用户验证相关的数据加密保存在客户端
            role: 1,
        }
        done(null, data, payload);
    }
}

export = function () {
    const app = this

    const config = app.get('authentication');
    //local, jwt
    app.configure(auth(config));
    const settingsJWT = {
        Verifier: CustomVerifier,
        //from cookies
        jwtFromRequest: jwt.ExtractJwt.fromExtractors([function (req: any) {
            var token = null;
            if (req && req.cookies) {
                token = req.cookies[config.cookie.name];
            }
            return token;
        }]),
        //from auth header (TODO 不知道为什么不生效)
        // jwtFromRequest: jwt.ExtractJwt.fromHeader('Authorization'),
    }
    app.configure(jwt(settingsJWT));
    app.configure(local(config.local));

    // The `authentication` service is used to create a JWT.
    // The before `create` hook registers strategies that can be used
    // to create a new valid JWT (e.g. local or oauth2)
    app.service('authentication').hooks({
        before: {
            create: [
                auth.hooks.authenticate(config.strategies)
            ],
            remove: [
                auth.hooks.authenticate('jwt')
            ]
        }
    })

    //jwt
    // const settingsDefault = app.get('authentication')
    // const settingsAuth = {
    //     secret: settingsDefault.secret,
    //     path: `/${authServicePath}`, // the authentication service path
    //     header: 'Authorization', // the header to use when using JWT auth
    //     entity: 'user', // the entity that will be added to the request, socket, and hook.params. (ie. req.user, socket.user, hook.params.user)
    //     service: userService, // the service to look up the entity
    //     passReqToCallback: true, // whether the request object should be passed to the strategies `verify` function
    //     session: false, // whether to use sessions
    //     cookie: {
    //         enabled: true, // whether the cookie should be enabled
    //         name: cookieName, // the cookie name
    //         httpOnly: false, // whether the cookie should not be available to client side JavaScript
    //         secure: false // whether cookies should only be available over HTTPS
    //     },
    //     jwt: {
    //         header: { type: 'access' }, // by default is an access token but can be any type
    //         audience: 'https://kollway.com', // The resource server where the token is processed
    //         subject: 'anonymous', // Typically the entity id associated with the JWT
    //         issuer: 'kollway', // The issuing server, application or resource
    //         algorithm: 'HS256', // the algorithm to use
    //         expiresIn: app.get('auth_expire'), // the access token expiry
    //         ignoreExpiration: false,
    //     }
    // }
    // const settingsJWT = {
    //     Verifier: CustomVerifier,
    //     //from cookies
    //     jwtFromRequest: jwt.ExtractJwt.fromExtractors([function (req: any) {
    //         var token = null;
    //         if (req && req.cookies) {
    //             token = req.cookies[settingsAuth.cookie.name];
    //         }
    //         return token;
    //     }]),
    // }
    // app.configure(auth(settingsAuth))
    // app.configure(jwt(settingsJWT))

    // const isUseLogin = () => {
    //     return (hook: any) => {
    //         return hook.data.email && hook.data.password
    //     }
    // }
    // const checkLogin = () => {
    //     return (hook: any) => {
    //         //TODO 检测登录
    //         if (hook.data.email == 'admin@feathersjs.com' && hook.data.password == '123456') {
    //             hook.result = {
    //                 ...hook.result,
    //                 ...hook.data,
    //             }
    //             return Promise.resolve(hook)
    //         } else {
    //             let error = new errors.NotAuthenticated('登录失败')
    //             return Promise.reject(error)
    //         }
    //     }
    // }
    // const issueJWT = require('./issueJWT.hook')
    // // const renewToken = require('./renewToken.hook')
    // app.service(`/${authServicePath}`).hooks({
    //     before: {
    //         create: [iffElse(isUseLogin(), checkLogin(), auth.hooks.authenticate('jwt'))]
    //     },
    //     after: {
    //         create: [issueJWT()]
    //     }
    // });
}